package com.leyou.user.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.common.utils.NumberUtils;
import com.leyou.item.pojo.Sku;
import com.leyou.user.interceptor.LoginInterceptor;
import com.leyou.user.mapper.*;
import com.leyou.user.pojo.Collect;
import com.leyou.user.pojo.User;
import com.leyou.user.pojo.UserAddress;
import com.leyou.user.pojo.UserDetail;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate template;
    @Autowired
    private UserDetailMapper detailMapper;

    @Autowired
    private UserAddressMapper addressMapper;
    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private SkuMapper skuMapper;

    private static final String USER_CODE_PREFIX = "leyou:user:code:";

    public Boolean checkUser(String data, Integer type) {

        User record = new User();
        switch (type) {
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                return null; // 参数不合法
        }
        // 响应用户名或者手机号是否可用
        return this.userMapper.selectCount(record) == 0;
    }

    public void sendCode(String phone) {

        // 生成验证码
        String code = NumberUtils.generateCode(6);

        // 保存到redis中
        this.redisTemplate.opsForValue().set(USER_CODE_PREFIX + phone, code, 5, TimeUnit.MINUTES);

        // 发送消息给sms服务
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        this.template.convertAndSend("leyou.sms.exchange", "sms.register", map);
    }

    public Boolean register(User user, String code) {

        // 从redis中获取本地验证码
        String redisCode = this.redisTemplate.opsForValue().get(USER_CODE_PREFIX + user.getPhone());
        // 和用户提交的验证码，比较
        if (!StringUtils.equals(code, redisCode)) {
            return null;
        }
        // 校验通过，对密码加密
        String salt = CodecUtils.generateSalt();
        String password = CodecUtils.md5Hex(user.getPassword(), salt);

        // 保存用户信息
        user.setPassword(password);
        user.setSalt(salt);
        user.setCreated(new Date());
        return this.userMapper.insertSelective(user) == 1;
    }

    public User queryUser(String username, String password) {
        // 根据用户名查询用户
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);

        // 如果用户为null
        if (user == null) {
            return null;
        }

        // 比较密码是否正确
        password = CodecUtils.md5Hex(password, user.getSalt());
        if (!StringUtils.equals(password, user.getPassword())) {
            return null;
        }

        // 比较成功
        return user;
    }


    public PageResult<Collect> queryCollectionByUserId(Integer page, Integer rows) {
        // 获取userID
        UserInfo loginUserInfo = LoginInterceptor.getLoginUserInfo();
        Long userId = loginUserInfo.getId();
        Collect collect = new Collect();
        collect.setUserId(userId);
        // 开始分页
        PageHelper.startPage(page, rows);
        // 根据userId查询，获取用户收藏
        Page<Collect> pageInfo = (Page<Collect>) this.collectMapper.select(collect);
        // 更新收藏商品的最新信息
        List<Collect> collects = pageInfo.getResult();
        collects.forEach(c -> {
            Sku sku = this.skuMapper.selectByPrimaryKey(c.getSkuId());
            if (sku == null) {
                // 该商品已经被修改或者删除，id不存在了，删除购物车中对应的商品`
                this.collectMapper.deleteByPrimaryKey(c.getId());
            } else {
                // 检查是否降价
                if (sku.getPrice() >= c.getPrice()) {
                    // 商品价格大于等于收藏时的价格，替换,未降价
                    c.setIsCut(false);
                } else if (sku.getPrice() < c.getPrice()) {
                    // 商品价格小于收藏时的价格，替换，并设置是否将价位true
                    c.setIsCut(true);
                }
                // 将价格更新
                c.setPrice(sku.getPrice());
                c.setTitle(sku.getTitle());
                c.setImage(StringUtils.isNotBlank(sku.getImages()) ? StringUtils.split(sku.getImages(), ",")[0] : "");

            }
        });
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), collects);
    }

    /**
     * 添加用户detail
     *
     * @param userDetail
     * @return
     * @LQB
     */
    public Boolean saveUserDetail(UserDetail userDetail) {

        //获取登陆用户ID
        Long id = LoginInterceptor.getLoginUserInfo().getId();

        userDetail.setUid(id);
        UserDetail user = this.detailMapper.selectByPrimaryKey(id);

        if (user == null) {
            //用户添加的信息不存在时，添加
            return this.detailMapper.insertSelective(userDetail) == 1;
        }
        //已经存在，根据id更新
        return this.detailMapper.updateByPrimaryKey(userDetail) == 1;

    }

    /**
     * 添加用户address
     *
     * @param userAddress
     * @return
     */
    public Boolean addUserDetail(@Valid UserAddress userAddress) {
        //获取登陆用户ID
        Long id = LoginInterceptor.getLoginUserInfo().getId();
        userAddress.setUid(id);
        return this.addressMapper.insertSelective(userAddress) == 1;
    }

    /**
     * 查询用户详细信息
     *
     * @param id
     * @return
     */
    public UserDetail queryUserDetail(Long id) {
        UserDetail userDetail = this.detailMapper.selectByPrimaryKey(id);

        return userDetail;
    }

    /**
     * 查詢用戶地址
     * @param id
     * @return
     */
    public List<UserAddress> queryUserAddress(Long id) {
        UserAddress userAddress = new UserAddress();
        userAddress.setUid(id);
        List<UserAddress> addressList = this.addressMapper.select(userAddress);
        return addressList;
    }
}
